<?php
/**
 * Created by PhpStorm.
 * User: HarrisHuang
 * Date: 17/5/31
 * Time: 13:17
 */
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Nav;
use Log;

class IndexNavController extends Controller
{

    public function save(Request $request, Nav $nav)
    {
        try {
            $nav->pic = $request->input('pic');
            $nav->name = $request->input('name');
            $nav->sort = $request->input('sort');
            $nav->type = 2;
            $nav->addTime = time();
            $nav->save();
        }catch (\Exception $e){
            Log::error('save banner error '.$e->getMessage());
            return $this->error();
        }
        return $this->success();
    }

    public function update(Request $request)
    {
        try {
            $all = $request->all();
            $ids = array_column($all, 'id');
            //先执行删除
            Nav::whereNotIn('id', $ids)
                ->where('type',2)
                ->delete();

            //新增或修改
            foreach ($all as $v) {
                if (isset($v['id'])) {
                    Nav::where('id', $v['id'])
                        ->update([
                            'name' => $v['name'],
                            'pic' => $v['pic'],
                            'sort' => $v['sort'],
                            'link' => $v['link'],
                        ]);
                } else {
                    Nav::create([
                        'name' => $v['name'],
                        'pic' => $v['pic'],
                        'sort' => $v['sort'],
                        'link' => $v['link'],
                        'addTime' => time(),
                        'type' => 2
                    ]);
                }
            }
        }catch (\Exception $e){
            Log::error(' 保存修改nav失败 error='.$e->getMessage());
            return $this->error();
        }
        return $this->success();


    }

    public function delete(Request $request)
    {
        $id = (int)$request->get('id');
        $res = Nav::destroy($id);
        if($res != 1){
            return $this->error();
        }
        return $this->success();
    }

    public function lists(Request $request)
    {
        $pageSize = $request->get('pageSize',10);
        $list = Nav::orderBy('sort','desc')->where('type',2)->paginate($pageSize);
        $list = $list->toArray();
        $res = [
            'total' => $list['total'],
            'data' => $list['data'],
        ];
        return $this->success($res);
    }

    public function mobileLists(Request $request)
    {
        $pageSize = $request->get('pageSize',10);
        $list = Nav::orderBy('sort','desc')->where('type',2)->paginate($pageSize);
        $list = $list->toArray();
        $res = [
            'total' => $list['total'],
            'data' => $list['data'],
        ];
        return $this->success($res);
    }

}